//*** Guidance generated code ***//
using System;
using System.Collections.Generic;

using System.Linq;
using NHibernate.Criterion;

using ProjectBase.Core;
using ProjectBase.Data;
using ProjectBase.Data.NH;

using $prjsn$.Entity;
using $prjsn$.Common;
using $prjsn$.Common.Data;

namespace $safeprojectname$
{
    public abstract class FieldObjectDao<TField>
        : BaseDao<TField, int, FieldFilter>
        , IFieldObjectDao<TField>
        where TField : FieldObject
    {
        public override IEnumerable<TField> Find(FieldFilter filter)
        {
            Criteria.Append(Apply(filter));

            return GetListByCriteria(filter);
        }

        #region IApplyFilterToCriteria

        protected override IList<ICriterion> Apply(FieldFilter filter)
        {
            var restrictions = base.Apply(filter);

            // Equal
            restrictions.AddCompare(filter, f => f.IdExact); // Searches for exact ID
            restrictions.AddIn(filter, f => f.IDColl);

            restrictions.AddEqual(filter, f => f.PropertyNameExact); // exact
            restrictions.AddEqual(filter, f => f.ColumnNameExact); // exact
            restrictions.AddEqual(filter, f => f.DisplayNameExact);

            // like
            restrictions.AddLike(filter, f => f.PropertyName);
            restrictions.AddLike(filter, f => f.ColumnName);
            restrictions.AddLike(filter, f => f.DisplayName);

            restrictions.AddLike(filter, f => f.DataType);

            // struct
            restrictions.AddIn(filter, f => f.IsStatic);
            restrictions.AddIn(filter, f => f.IsRequired);
            restrictions.AddIn(filter, f => f.IsUnique);

            // Limits
            restrictions.AddLike(filter, f => f.MinValue);
            restrictions.AddLike(filter, f => f.MaxValue);

            return restrictions;
        }

        #endregion IApplyFilterToCriteria

        #region override Add

        public override TField Add(TField entity)
        {
            var maxField = GetAll()
                .Where(field => !field.IsStatic)
                .OrderByDescending(e => e.ID)
                .FirstOrDefault();

            int maxId = maxField.Is() ? maxField.ID : 1000;

            entity.SetId(maxId + 1);

            return base.Add(entity);
        }

        #endregion override Add

        #region IFieldBaseDao

        public virtual IEnumerable<TField> GetAll()
        {
            return Find(new FieldFilter { TakeRows = int.MaxValue });
        }

        #endregion IFieldBaseDao
    }
}